package com.itzhoun.callback;

import com.itzhoun.client.MyMQTTClient;
import com.itzhoun.config.MqttConfiguration;
import com.itzhoun.util.SpringUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhounan
 * @date 2025/01/23 19:21
 * @Description
 */
public class MyMQTTCallback implements MqttCallbackExtended {

    private static final Logger log = LoggerFactory.getLogger(MyMQTTCallback.class);

    private MqttConfiguration mqttConfiguration = SpringUtils.getBean(MqttConfiguration.class);



    private MyMQTTClient mqttClient;

    public MyMQTTCallback(MyMQTTClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    /**
     *
     * 连接成功后的回调，订阅主题
     */
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        log.info("MQTT connect success. connect method:{}", reconnect? "直连":"重连");

        //订阅主题
        //手动注入主题
        mqttClient.subscribe(mqttConfiguration.getTopic1(), 1);
        mqttClient.subscribe(mqttConfiguration.getTopic2(), 1);
        mqttClient.subscribe(mqttConfiguration.getTopic3(), 1);
        mqttClient.subscribe(mqttConfiguration.getTopic4(), 1);

    }

    /**
     *
     * @Description 丢失连接，这里尝试重连
     * 只会掉用一次
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("mqtt connectionLost 连接断开，5s后尝试重新连接：{} ", throwable.getMessage());
        long reconnectTimes = 1;
        while (true){
            try {
                if (MyMQTTClient.getClient().isConnected()){
                    log.warn("MQTT reconnect success end 重新连接成功");
                    return;
                }

                reconnectTimes +=1;
                log.warn("mqtt reconnect times ={} try again... mqtt重新连接时间:{}", reconnectTimes, reconnectTimes);
                MyMQTTClient.getClient().reconnect();
            } catch (MqttException e) {
                log.error("mqtt 断开连接", e);
            }
            try {
                Thread.sleep(5000);
            }catch (InterruptedException e){

            }

        }


    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        log.info("接收消息主题：{}, 接收消息内容：{}", topic, new String(mqttMessage.getPayload()));

        //todo 这地方处理得考虑不同的主题来处理了、、
        //发布消息主题
        if (topic.equals("embed/resp")){
//            Map maps = (Map)JSON.parse(new String(mqttMessage.getPayload(), StandardCharsets.UTF_8));
            //你自己的业务接口
            System.out.println("-----------------");
        }
        //接收报警主题
        if (topic.equals("embed/warn")){
//            Map maps = (Map) JSON.parse(new String(mqttMessage.getPayload(), StandardCharsets.UTF_8));
            //你自己的业务接口
            System.out.println("---------------");
        }


    }

    /**
     *
     * 消息到达后，subscribe后执行的回调函数
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("===============deliveryComplete{}==========", iMqttDeliveryToken.isComplete());

    }
}
